<template>
  <div class="home-wrapper">
    <div class="home-header clearfix">
      <span @click="selectYear">{{currentYearName}}<i class="el-icon-caret-bottom"></i></span>
      <span @click="selectSeason">{{currentSeasonName}}<i class="el-icon-caret-bottom"></i></span>
      <span class="search-bar" @click="openSet"><i class="el-icon-more"></i></span>
    </div>
    <div class="goal-type">
      <span @click="selectType">{{currentTypeName}}OKR<i class="el-icon-arrow-down"></i></span>
    </div>
    <div class="home-content">
      <div class="goal-list" ref="scrollcontainer" v-infinite-scroll="loadData" infinite-scroll-disabled="disabled" infinite-scroll-immediate="false">
        <div class="goal" v-for="goal in goalList" :key="goal.id" @click="openGoalDetail(goal.id)">
          <span class="arrow-status" :class="getArrowType(goal)"></span>
          <span class="goal-status">{{getWord(goal)}}</span>
          <div class="progress">
            <el-progress :width="40" :stroke-width="3" type="circle" :percentage="goal.goalProgressPercent || 0"></el-progress>
          </div>
          <div class="goal-info">
            <p class="title">{{goal.goalName}}</p>
            <p class="name"><span>{{goal.goalTag === '1'? '公司': goal.goalTag === '2'? '部门': '团队'}}级</span><span v-if="goal.goalExecuteDepartmentName">{{goal.goalExecuteDepartmentName? goal.goalExecuteDepartmentName: ''}}{{goal.goalPrincipalName? `(${goal.goalPrincipalName})`: ''}}</span></p>
          </div>
        </div>
      </div>
    </div>
    <div class="home-footer clearfix">
      <div class="add-btn" @click.stop="openAddGoal">
        <i class="el-icon-plus"></i> 目标
      </div>
    </div>
    <Goal ref="goal" @reload="reload" :postFormYear.sync="currentYear" :postFormYearName.sync="currentYearName" :postFormSeason.sync="currentSeason" :postFormSeasonName.sync="currentSeasonName" />
    <div class="select-dept" v-if="showDepart">
      <div class="mask" ref="selectmask" @click.stop="closeSelect"></div>
      <div :class="animationName" class="department">
        <div class="dept-header">
          <i class="el-icon-arrow-down" @click.stop="closeSelect"></i>
          <span @click.stop="backOrigin">公司部门</span>
          <span v-for="(path, idx) in pathArr" :key="path.id" @click.stop="openNext(path,idx)"><i class="el-icon-arrow-right"></i>{{path.departmentName}}</span> 
        </div>
        <div class="dept-list">
          <div class="dept-item" @click.stop="selectDept(dept.id)" v-for="dept in deptShow" :key="dept.id">
            <div class="dept-name">{{dept.departmentName}} {{dept.departmentPrincipalName? `(${dept.departmentPrincipalName})`: ''}}</div>
            <div class="dept-next" @click.stop="openNext(dept)"><img src="../../../assets/img/xiaji.png" alt="">下级</div>
          </div>
        </div>
        <div class="add-btn" v-if="isManager1" @click="addDept"><i class="el-icon-plus"></i></div>
      </div>
    </div>
    <div class="dept-form" v-if="showDeptForm">
      <div class="mask" ref="formmask" @click.stop="closeForm"></div>
      <div :class="animationName2" class="department">
        <div class="dept-header">
          <i class="el-icon-arrow-down" @click.stop="closeForm"></i>
          <span>编辑组织架构</span>
        </div>
        <div class="dept-detail">
          <div class="form-item clearfix">
            <div class="label" @click.stop="backOrigin">上级部门</div>
            <div class="input">{{deptForm.departmentBelongName}}</div>
          </div>
          <div class="form-item">
            <textarea class="goal-name" :readonly="checkDeptForm" v-model="deptForm.departmentName" placeholder="输入名称：力往一处使，确保目标上下对齐"></textarea>
          </div>
          <div class="form-item clearfix">
            <div class="label">执行人</div>
            <div class="input" @click.stop="selectDingUsers">{{deptForm.departmentPrincipalName}}<i class="el-icon-arrow-right"></i></div>
          </div>
        </div>
        <div class="goal-button" v-if="!checkDeptForm">
          <div @click="saveDept">保存</div>
        </div>
        <div class="add-btn" v-if="deptForm.id && checkDeptForm && isManager1" @click="deptAction"><i class="el-icon-menu"></i></div>
      </div>
    </div>
  </div>
</template>

<script>
import dingMixin from  '@/mixins/ding'
import {dateUtil} from '@/utils/dateUtil'
import formUtil from "@/utils/formUtil";
import Goal from './Goal'
import AtTa from 'vue-at/dist/vue-at-textarea'

export default {
  data() {
    return {
      showDeptForm: false,
      goalList: [],
      showAddGoal: false,
      showDepart: false,
      showKr: false,
      projectList: [],
      animationName: 'open',
      animationName2: 'open',
      currentTypeName: '全部',
      currentType: '',
      searchPost:{
        goalExecuteDepartmentId: '',
        goalPeriodYear: '',
        goalPeriodTime: '',
        krDataType: '',
        goalTag: '',
        page: 1,
        limit: 999
      },
      isFirstLoading: false,
      loading: false,
      totalPage: 0,
      yearArr: [],
      seasonArr: [{
        value: `0201`,
        key: '第1季度LKR'
      },{
        value: `0202`,
        key: '第2季度LKR'
      },{
        value: `0203`,
        key: '第3季度LKR'
      },{
        value: `0204`,
        key: '第4季度LKR'
      },{
        value: `0200`,
        key: '年度LKR'
      }],
      currentYear: '',
      currentYearName: '',
      currentSeason: '',
      currentSeasonName: '',
      formTime: '',
      formTimeName: '',
      deptTotal: [],
      deptShow: [],
      pathArr: [],
      deptForm: {
        departmentName: '',
        departmentPrincipalId: '',
        departmentPrincipalName: '',
        departmentBelongId: '',
        departmentBelongName: '',
        departmentLevel: ''
      },
      deptFormVerify: {
        departmentName: '请输入部门或团队名称'
      },
      checkDeptForm: true,
      currentScrollTop: 0,
      isManager1: false,
      deptArr: []
    }
  },
  components: {
    Goal,AtTa
  },
  mixins: [dingMixin],
  computed: {
    disabled () {
      return this.isFirstLoading || this.loading || this.noMore
    },
    noMore () {
      return this.searchPost.page >= this.totalPage;
    }
  },
  mounted() {
    this.setTimeArr();
    this.getGoalList(true);
    this.getAllDept();
    this.getAuth();
  },
  beforeRouteLeave(to,from,next) {
    this.currentScrollTop = this.$refs.scrollcontainer.scrollTop;
    this.mobileStopRefresh()
    next()
  },
  activated() {
    this.mobileGetDevice(({model, brand, version}) => {
      if(brand !== 'OnePlus') {
        this.mobildPullToRefresh(() => {
          this.getGoalList(true)
        });
      }
    })
    if(window.NEEDREFRESH) {
      this.getGoalList(true)
      window.NEEDREFRESH = false;
    }else {
      this.$refs.scrollcontainer.scrollTop = this.currentScrollTop;
    }
  },
  methods: {
    async getAuth() {
      let auth = await this.$httpN.postB('lkr/organization/asd');
      if(auth.userLevel === '1') this.isManager1 = true;
    },
    getArrowType(item) {
      if(item.goalStatus === '1') {
        return 'arrow-1'
      }else if(item.goalStatus === '2') {
        return 'arrow-2'
      }else if(item.goalStatus === '3') {
        return 'arrow-3'
      }
    },
    getWord(item) {
      if(item.goalStatus === '1') {
        return '拟定状态'
      }else if(item.goalStatus === '2') {
        return '执行状态'
      }else if(item.goalStatus === '3') {
        return '完成状态'
      }
    },
    async saveDept() {
      if(!formUtil.verifyData(this.deptForm, this.deptFormVerify)) return;
      if (!(await this.$httpN.postB(this.deptForm.id ? 'lkr/organization/departmentUpdate': 'lkr/organization/departmentSave', this.deptForm))) return;
      this.mobileMessage('保存成功');
      this.deptTotal = await this.$httpN.postB('lkr/organization/organization');
      this.deptShow = this.deptTotal.filter(item => item.departmentBelongId === ((this.pathArr[this.pathArr.length - 1] && this.pathArr[this.pathArr.length - 1].id) || ''));
      this.closeForm();
    },
    selectDingUsers() {
      if(this.checkDeptForm) return;
      this.complexPicker(1, [], [this.deptForm.departmentPrincipalId]).then(
        data => {
          this.deptForm.departmentPrincipalId = data[0].emplId;
          this.deptForm.departmentPrincipalName = data[0].name;
        }
      );
    },
    async getAllDept() {
      this.deptTotal = await this.$httpN.postB('lkr/organization/organization');
      this.deptShow = this.deptTotal.filter(item => !item.departmentBelongId);
    },
    addDept() {
      formUtil.resetData(this.deptForm);
      this.checkDeptForm = false;
      this.deptForm.departmentBelongId = (this.pathArr[this.pathArr.length - 1] && this.pathArr[this.pathArr.length - 1].id) || '';
      this.deptForm.departmentBelongName = (this.pathArr[this.pathArr.length - 1] && this.pathArr[this.pathArr.length - 1].departmentName) || '';
      this.deptForm.departmentLevel = (this.pathArr[this.pathArr.length - 1] && parseInt(this.pathArr[this.pathArr.length - 1].departmentLevel) + 1) || 1;
      this.openDeptForm();
    },
    async selectDept(id) {
      this.checkDeptForm = true;
      this.deptForm = await this.$httpN.postB('lkr/organization/info/' + id)
      this.openDeptForm();
    },
    backOrigin() {
      this.pathArr = [];
      this.deptShow = this.deptTotal.filter(item => item.departmentBelongId === '');
    },
    openNext(dept, idx){
      if(idx >= 0) {
        this.pathArr = this.pathArr.splice(0, (idx+1));
      }else{
        this.pathArr.push(dept);
      }
      this.deptShow = this.deptTotal.filter(item => item.departmentBelongId === dept.id);
    },
    deptAction() {
      this.mobileSelect('更多操作', ['编辑组织架构', '删除组织架构'],({buttonIndex}) => {
        if(buttonIndex === 0) {
          this.checkDeptForm = false;
        }else if(buttonIndex === 1){
          this.mobileConfirm('该组织架构下可能存在目标，您确定要删除吗', async ()=> {
            if(! await this.$httpN.postB("lkr/organization/departmentDelete", {id: this.deptForm.id})) return 
            this.mobileMessage('删除成功');
            this.deptTotal = await this.$httpN.postB('lkr/organization/organization');
            this.deptShow = this.deptTotal.filter(item => item.departmentBelongId === this.pathArr[this.pathArr.length - 1].id);
            this.closeForm();
          })
        }
      })
    },
    openSet() {
      this.mobileSelect('更多操作', ['调整组织架构', '关键结果统计'],({buttonIndex}) => {
        if(buttonIndex === 0) {
          this.backOrigin();
          this.showDepart = true;
          this.$nextTick(() => {
            this.$refs.selectmask.style.opacity = 0.5;
          })
        }else if(buttonIndex === 1) {
          this.$router.push({ name: 'mlkr-statistics'})
        }
      })
    },
    openDeptForm() {
      this.showDeptForm = true;
      this.$nextTick(() => {
        this.$refs.formmask.style.opacity = 0.5;
      })
    },
    reload() {
      this.getGoalList(true)
    },
    openAddGoal() {
      this.$refs.goal.openGoalDialog();
    },
    openGoalDetail(id) {
      this.$router.push({ name: 'mlkr-detail', params: {id}})
    },
    setTimeArr() {
      let year = parseInt((new Date).Format(`yyyy`));
      this.currentYear = `${year}`
      this.currentYearName = `${year}年`
      this.currentSeason = `02${(new Date).Format(`qq`)}`
      this.currentSeasonName = `第${(new Date).Format(`q`)}季度LKR`
      this.yearArr = []
      for (let i=-5; i<=5; i++) {
        this.yearArr.push({
          value: `${year-i}`,
          key: `${year-i}年`
        })
      }
    },
    async loadData() {
      this.loading = true;
      this.searchPost.page ++;
      await this.getGoalList();
    },
    
    async getGoalList(init) {
      if(init) {
        this.searchPost.page = 1;
        this.searchPost.goalPeriodYear = this.currentYear;
        this.searchPost.goalPeriodTime = this.currentSeason;
        this.searchPost.goalTag = this.currentType;
        this.goalList = [];
        this.isFirstLoading = true;
      }
      let {list, totalCount, totalPage} = await this.$httpN.postB('lkr/goal/goalList', this.searchPost)
      this.loading = false;
      this.goalList.push(...list);
      if(init) {
        this.totalPage = totalPage;
        this.$nextTick(() => {
          this.isFirstLoading = false;
        })
      }
    },
    closeForm() {
      this.animationName2 = 'close';
      this.$refs.formmask.style.opacity = 0;
      setTimeout(() => {
        this.showDeptForm = false;
        this.animationName2 = 'open';
      }, 225)
    },
    closeSelect() {
      this.animationName = 'close';
      this.$refs.selectmask.style.opacity = 0;
      setTimeout(() => {
        this.showDepart = false;
        this.animationName = 'open';
      }, 225)
    },
    selectYear() {
      this.mobileChosen(this.yearArr, this.currentYearName,(data) => {
        this.currentYear = data.value;
        this.currentYearName = data.key;
        this.getGoalList(true)
      })
    },
    selectSeason() {
      this.mobileChosen(this.seasonArr, this.currentSeasonName,(data) => {
        this.currentSeason = data.value;
        this.currentSeasonName = data.key;
        this.getGoalList(true)
      })
    },
    selectType() {
      this.mobileChosen([{key: '全部',value: ''}, {key: '公司级',value: '1'}, {key: '部门级',value: '2'}, {key: '团队级',value: '3'}], this.currentType,(data) => {
        this.currentTypeName = data.key;
        this.currentType = data.value;
        this.getGoalList(true)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .home-wrapper{
    height: 100vh;
    background: #F6F6F6;
    position: relative;
    .home-header{
      line-height: 46px;
      background: white;
      font-weight: bold;
      padding: 0 16px;
      .search-bar{
        float:right;
        >i:first-child{
          margin-right: 10px;
          font-size: 24px;
          position: relative;
          top: 4px;
        }
      }
    }
    .goal-type{
      margin-top: 10px;
      text-align: center;
    }
    .home-footer{
      position: absolute;
      bottom: 0;
      left: 0;
      height: 46px;
      background: white;
      width: 100%;
      line-height:46px;
      padding: 0 16px;
      .add-btn{
        float:right;
        line-height: 36px;
        height: 36px;
        color: white;
        background: #3396FB;
        margin-top: 5px;
        width: 100px;
        text-align: center;
        border-radius: 50px;
      }
    }
    .home-content{
      .goal-list{
        padding: 0 16px;
        margin-top: 10px;
        height: calc(100vh - 130px);
        overflow-y: auto;
        .goal{
          height: 80px;
          background: white;
          margin-bottom: 10px;
          display: flex;
          border-radius: 4px;
          box-shadow: 0 1px 3px rgb(221, 221, 221);
          position: relative;
          .arrow-status{
            width:0;
            height:0;
            position: absolute;
            top: 0;
            left: 0;
            border-top-left-radius: 5px;
            border-top:solid 20px #21D779;
            border-left:solid 20px #21D779 ;
            border-bottom:solid 20px transparent;
            border-right:solid 20px transparent;      
            &.arrow-1{
              border-top:solid 20px #4495FF;
              border-left:solid 20px #4495FF ;
            }
            &.arrow-2{
              border-top:solid 20px #21D779;
              border-left:solid 20px #21D779 ;
            }
            &.arrow-3{
              border-top:solid 20px #DBDADA;
              border-left:solid 20px #DBDADA ;
            }
          }
          .goal-status{
            position: absolute;
            width: 60px;
            line-height: 20px;
            left: -14px;
            top: 5px;
            color: white;
            font-size: 12px;
            transform: rotate(-45deg) scale(0.7);
            text-align: center;
            font-weight: normal;
          }
          &::after{
            content: '';
            width:0;
            height:0;
            position: absolute;
            top: 0;
            left: 0;
            border-top-left-radius: 5px;
            border-top:solid 10px white;
            border-left:solid 10px white ;
            border-bottom:solid 10px transparent;
            border-right:solid 10px transparent;
          }
          .progress{
            width: 80px;
            padding-top:20px;
            padding-left: 20px;
          }
          .goal-info{
            width:calc(100% - 80px);
            padding-top: 20px;
            p{
              margin: 0;
            }
            .title{
              font-weight: bold;
              font-size: 16px;
              width: 100%;
              white-space:nowrap;
              overflow:hidden;
              text-overflow:ellipsis;
            }
            .name{
              margin-top:5px;
              font-size:12px;
              >span:first-child{
                display: inline-block;
                margin-right: 10px;
                background: #C9E8FE;
                padding: 5px 7px;
                color: #3a8ee6;
                border-radius: 50px;
              }
              >span:last-child{
                display: inline-block;
                padding: 5px 7px;
                border:1px solid #ECECEC;
                border-radius: 50px;
              }
            }
          }
        }
      }
    }
  }
.select-dept .open{
  animation: btt-drawer-in 225ms cubic-bezier(0,0,.2,1) 0s;
}
.select-dept .close{
  animation: btt-drawer-out 225ms cubic-bezier(0,0,.2,1) 0s;
}
.select-dept{
  height: 100vh;
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  z-index: 10;
  .mask{
    background: rgb(0,0,0);
    height: 100%;
    position: absolute;
    top:0;
    left:0;
    transition: all 225ms;
    width: 100%;
    opacity: 0;
  }
  .department{
    border-radius: 15px 15px 0 0 ;
    height: 90vh;
    background: white;
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    background: #F6F6F6;
    .dept-header{
      border-radius: 15px 15px 0 0 ;
      height: 46px;
      line-height: 46px;
      padding:0 16px;
      color: #3296FA;
      background: white;
      white-space: nowrap;
      overflow-x: auto;
      i{
        margin-right: 3px;
        color: #909399;
      }
    }
    .add-btn {
      position: absolute;
      right: 20px;
      bottom: 20px;
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background-color: #409EFF;
      background-image: linear-gradient(#79BBFF, #409EFF);
      box-shadow: 1px 1px 1px rgb(221, 221, 221);
      text-align: center;
      color: #FFF;
      font-size: 1.5rem;
      line-height: 40px;
      z-index: 3;
    }
    .dept-list{
      margin-top: 10px;
      background: white;
      padding: 0 16px;
      .dept-item{
        height: 50px;
        line-height: 50px;
        position: relative;
        border-bottom: 1px solid #f6f6f6;
        .dept-name{
          font-weight: bold;
        }
        .dept-next{
          position: absolute;
          top: 0;
          right: 0;
          height: 46px;
          color: #8a8a8a;
          img{
            width: 12px;
            position: relative;
            top: -1px;
          }
        }
      }
      >div:last-child{
        border-bottom: none;
      }
    }
    
  }
}


.dept-form .open{
  animation: btt-drawer-in 225ms cubic-bezier(0,0,.2,1) 0s;
}
.dept-form .close{
  animation: btt-drawer-out 225ms cubic-bezier(0,0,.2,1) 0s;
}
.dept-form{
  height: 100vh;
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  z-index: 10;
  .mask{
    background: rgb(0,0,0);
    height: 100%;
    position: absolute;
    top:0;
    left:0;
    transition: all 225ms;
    width: 100%;
    opacity: 0;
  }
  .department{
    border-radius: 15px 15px 0 0 ;
    height: 90vh;
    background: white;
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    background: #F6F6F6;
    .dept-header{
      border-radius: 15px 15px 0 0 ;
      height: 46px;
      line-height: 46px;
      padding:0 16px;
      background: white;
      white-space: nowrap;
      overflow-x: auto;
      text-align: center;
      position: relative;
      i{
        margin-right: 3px;
        color: #909399;
        position: absolute;
        left: 16px;
        top: 16px;
      }
    }
    .add-btn {
      position: absolute;
      right: 20px;
      bottom: 20px;
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background-color: #409EFF;
      background-image: linear-gradient(#79BBFF, #409EFF);
      box-shadow: 1px 1px 1px rgb(221, 221, 221);
      text-align: center;
      color: #FFF;
      font-size: 1.5rem;
      line-height: 40px;
      z-index: 3;
    }
    .dept-detail{
      margin-top: 10px;
      .form-item{
        background: white;
        padding: 6px 12px;
        border-bottom: 1px solid #ECECEC;
        .goal-name{
          font-size: 18px;
          width: 100%;
          height: 60px;
          border: none;
          outline: none;
          resize:none;
          background: transparent;
        }
        .label{
          float:left;
          line-height: 46px;
          font-size:15px;
        }
        .input{
          float:right;
          line-height: 46px;
          min-width: 40px;
          text-align: right;
        }
      }
    }
  }
}

.goal-button{
  height: 50px;
  background: white;
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 6px 12px;
  div{
    text-align: center;
    width: 100%;
    background: #3396FB;
    line-height: 36px;
    color: white;
    border-radius: 5px;
  }
}

</style>